<template>
  <div class="notification-container">
    <!-- 通知图标和未读数量 -->
    <div class="notification-icon" @click="toggleNotificationPanel">
      <el-badge :value="unreadCount" :hidden="unreadCount === 0" class="notification-badge">
        <el-icon size="20">
          <Bell />
        </el-icon>
      </el-badge>
    </div>

    <!-- 通知面板 -->
    <div v-if="showNotificationPanel" class="notification-panel">
      <div class="notification-header">
        <h3>通知中心</h3>
        <div class="header-actions">
          <el-button size="small" @click="markAllAsRead" :disabled="unreadCount === 0">
            全部已读
          </el-button>
          <el-button size="small" @click="refreshNotifications">
            刷新
          </el-button>
        </div>
      </div>

      <!-- 通知列表 -->
      <div class="notification-list">
        <div 
          v-for="notification in notifications" 
          :key="notification.id"
          class="notification-item"
          :class="{ 'unread': !notification.isRead }"
          @click="markAsRead(notification.id)"
        >
          <div class="notification-content">
            <div class="notification-title">
              <el-tag :type="getPriorityType(notification.priority)" size="small">
                {{ notification.typeName }}
              </el-tag>
              {{ notification.title }}
            </div>
            <div class="notification-message">{{ notification.content }}</div>
            <div class="notification-meta">
              <span class="notification-time">{{ formatTime(notification.createTime) }}</span>
              <el-button 
                v-if="!notification.isRead" 
                size="small" 
                type="primary" 
                link
                @click.stop="markAsRead(notification.id)"
              >
                标记已读
              </el-button>
              <el-button 
                size="small" 
                type="danger" 
                link
                @click.stop="deleteNotification(notification.id)"
              >
                删除
              </el-button>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-if="notifications.length === 0" class="empty-state">
          <el-empty description="暂无通知" />
        </div>
      </div>

      <!-- 分页 -->
      <div v-if="totalCount > pageSize" class="notification-pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50]"
          :total="totalCount"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Bell } from '@element-plus/icons-vue'
import * as signalR from '@microsoft/signalr'

// 响应式数据
const showNotificationPanel = ref(false)
const notifications = ref([])
const unreadCount = ref(0)
const totalCount = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const loading = ref(false)

// SignalR连接
const connection = ref(null)
const isConnected = ref(false)

// API基础URL
const API_BASE_URL = 'http://localhost:5097'

// 计算属性
const userId = computed(() => {
  // 从用户状态或localStorage获取当前用户ID
  return parseInt(localStorage.getItem('userId') || '1')
})

// 初始化SignalR连接
const initSignalR = async () => {
  try {
    console.log('正在初始化SignalR连接...')
    
    connection.value = new signalR.HubConnectionBuilder()
      .withUrl(`${API_BASE_URL}/notificationHub`)
      .withAutomaticReconnect()
      .build()

    // 监听实时通知
    connection.value.on('ReceiveNotification', (notification) => {
      console.log('收到实时通知:', notification)
      
      // 添加到通知列表顶部
      notifications.value.unshift(notification)
      
      // 更新未读数量
      if (!notification.isRead) {
        unreadCount.value++
      }
      
      // 显示通知提示
      ElMessage({
        message: notification.content,
        type: 'info',
        duration: 3000
      })
    })

    // 连接状态变化
    connection.value.onclose(() => {
      isConnected.value = false
      console.log('SignalR连接已断开')
    })

    connection.value.onreconnecting(() => {
      console.log('SignalR正在重连...')
    })

    connection.value.onreconnected(() => {
      isConnected.value = true
      console.log('SignalR重连成功')
    })

    // 启动连接
    await connection.value.start()
    isConnected.value = true
    console.log('SignalR连接成功')
    
  } catch (error) {
    console.error('SignalR连接失败:', error)
  }
}

// 获取通知列表
const getNotifications = async () => {
  try {
    loading.value = true
    const response = await fetch(`${API_BASE_URL}/api/Notification/list?userId=${userId.value}&pageIndex=${currentPage.value}&pageSize=${pageSize.value}`)
    const result = await response.json()
    
    if (result.code === 'Success') {
      notifications.value = result.data.pageDatas
      totalCount.value = result.data.totalCount
    } else {
      ElMessage.error(result.msg || '获取通知列表失败')
    }
  } catch (error) {
    console.error('获取通知列表失败:', error)
    ElMessage.error('获取通知列表失败')
  } finally {
    loading.value = false
  }
}

// 获取未读通知数量
const getUnreadCount = async () => {
  try {
    const response = await fetch(`${API_BASE_URL}/api/Notification/unread-count?userId=${userId.value}`)
    const result = await response.json()
    
    if (result.code === 'Success') {
      unreadCount.value = result.data
    }
  } catch (error) {
    console.error('获取未读通知数量失败:', error)
  }
}

// 标记通知为已读
const markAsRead = async (notificationId) => {
  try {
    const response = await fetch(`${API_BASE_URL}/api/Notification/mark-read`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        notificationId: notificationId,
        userId: userId.value
      })
    })
    
    const result = await response.json()
    
    if (result.code === 'Success') {
      // 更新本地状态
      const notification = notifications.value.find(n => n.id === notificationId)
      if (notification && !notification.isRead) {
        notification.isRead = true
        unreadCount.value--
      }
      
      ElMessage.success('标记已读成功')
    } else {
      ElMessage.error(result.msg || '标记已读失败')
    }
  } catch (error) {
    console.error('标记已读失败:', error)
    ElMessage.error('标记已读失败')
  }
}

// 标记所有通知为已读
const markAllAsRead = async () => {
  try {
    const response = await fetch(`${API_BASE_URL}/api/Notification/mark-all-read`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        userId: userId.value
      })
    })
    
    const result = await response.json()
    
    if (result.code === 'Success') {
      // 更新本地状态
      notifications.value.forEach(notification => {
        notification.isRead = true
      })
      unreadCount.value = 0
      
      ElMessage.success('全部标记已读成功')
    } else {
      ElMessage.error(result.msg || '标记全部已读失败')
    }
  } catch (error) {
    console.error('标记全部已读失败:', error)
    ElMessage.error('标记全部已读失败')
  }
}

// 删除通知
const deleteNotification = async (notificationId) => {
  try {
    await ElMessageBox.confirm('确定要删除这条通知吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await fetch(`${API_BASE_URL}/api/Notification/delete`, {
      method: 'DELETE',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        notificationId: notificationId,
        userId: userId.value
      })
    })
    
    const result = await response.json()
    
    if (result.code === 'Success') {
      // 从本地列表中移除
      const index = notifications.value.findIndex(n => n.id === notificationId)
      if (index > -1) {
        const notification = notifications.value[index]
        notifications.value.splice(index, 1)
        
        // 更新未读数量
        if (!notification.isRead) {
          unreadCount.value--
        }
      }
      
      ElMessage.success('删除成功')
    } else {
      ElMessage.error(result.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除通知失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 刷新通知
const refreshNotifications = () => {
  getNotifications()
  getUnreadCount()
}

// 切换通知面板
const toggleNotificationPanel = () => {
  showNotificationPanel.value = !showNotificationPanel.value
  if (showNotificationPanel.value) {
    refreshNotifications()
  }
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  getNotifications()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getNotifications()
}

// 获取优先级类型
const getPriorityType = (priority) => {
  switch (priority) {
    case 1: return 'info'
    case 2: return 'primary'
    case 3: return 'warning'
    case 4: return 'danger'
    default: return 'primary'
  }
}

// 格式化时间
const formatTime = (timeString) => {
  const time = new Date(timeString)
  const now = new Date()
  const diff = now - time
  
  if (diff < 60000) return '刚刚'
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`
  if (diff < 604800000) return `${Math.floor(diff / 86400000)}天前`
  
  return time.toLocaleDateString()
}

// 组件挂载
onMounted(() => {
  initSignalR()
  getUnreadCount()
})

// 组件卸载
onUnmounted(() => {
  if (connection.value) {
    connection.value.stop()
  }
})
</script>

<style scoped>
.notification-container {
  position: relative;
  display: inline-block;
}

.notification-icon {
  cursor: pointer;
  padding: 8px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.notification-icon:hover {
  background-color: #f5f5f5;
}

.notification-badge {
  position: relative;
}

.notification-panel {
  position: absolute;
  top: 100%;
  right: 0;
  width: 400px;
  max-height: 600px;
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  z-index: 1000;
  overflow: hidden;
}

.notification-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #e4e7ed;
  background: #fafafa;
}

.notification-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.notification-list {
  max-height: 400px;
  overflow-y: auto;
}

.notification-item {
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.3s;
}

.notification-item:hover {
  background-color: #f5f5f5;
}

.notification-item.unread {
  background-color: #f0f9ff;
  border-left: 3px solid #409eff;
}

.notification-content {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.notification-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
  font-size: 14px;
}

.notification-message {
  color: #666;
  font-size: 13px;
  line-height: 1.4;
}

.notification-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 8px;
}

.notification-time {
  color: #999;
  font-size: 12px;
}

.empty-state {
  padding: 40px 20px;
  text-align: center;
}

.notification-pagination {
  padding: 16px;
  border-top: 1px solid #e4e7ed;
  background: #fafafa;
}
</style>








